import React from 'react';
import TableStore, {ColumnProps} from '../../../stores/mobxTable/table';
import {observer} from 'mobx-react';
import Input from './Input';
import InputNumber from './InputNumber';
import Select from './Select';
import InputPopover from './InputPopover';
import Checkbox from './Checkbox';
import ShowDialog from './ShowDialog';
import Browser from './Browser';
import WeaDatePicker from './WeaDatePicker';
import WeaTimePicker from './WeaTimePicker';
import WeaTextarea from './WeaTextarea';
import jQuery from 'jquery';
import {Badge} from 'antd';
import {WeaTag,WeaInputLocale} from 'ecCom';
import Upload from './Upload'
import WeaDateTimePicker from './WeaDateTimePicker';
const getMultiStrFromBase64 = WeaInputLocale.getMultiStrFromBase64
const getCurrentLabel  = WeaInputLocale.getCurrentLabel 
export interface TableCellProps {
    tableStore: TableStore;
    column: ColumnProps
    randomkey: string;
    editable?: boolean;
    isNoSwitchEditStatus?: boolean;//是否去掉鼠标点击切换修改状态
    isfrontmultlang?: boolean;
}

@observer
export default class TableCell extends React.Component<TableCellProps, any> {
    constructor(props) {
        super(props);
        this.state = {_column: {}};
    }

    renderEditor = () => {
        const {randomkey, tableStore, isNoSwitchEditStatus, isfrontmultlang} = this.props;
        let {column} = this.props;
        column = {...column, ...this.state._column};
        const form = tableStore.form.$('tableForm');
        const row = form.$(randomkey);
        const field = row.$(column.key);
        const bindObj = field.bind();
        if (isNoSwitchEditStatus && column.viewAttr != 1) bindObj.editable = true;
        let conditionType = column.conditionType.toLowerCase();
        const commonProps = {
            autoFocus: false,
            onChange: this.handleChange,
            editable: !bindObj.disabled && bindObj.editable && column.viewAttr != 1,
            disabled: bindObj.disabled,
            row,
            field,
            column,
            isfrontmultlang: column.detailtype == '1' && conditionType == 'input' ? isfrontmultlang : false
        
        } as any;

        conditionType = this.state._conditionType || conditionType;
        if (conditionType == 'htmlinput') {
            return <span dangerouslySetInnerHTML={{__html: bindObj.value}}></span>
        } else if (conditionType == 'input') { //文本框
            if (column.detailtype == '2' || column.detailtype == '3') { //整数
                return (
                    <InputNumber
                        {...commonProps}
                        maxLength={column.maxLength}
                        reg={column.reg}
                        value={bindObj.value}
                        min={column.min}
                        max={column.max}
                        qfws={column.qfw}
                        />
                        )
                    } else if (column.detailtype == '6') {
                        return (
                            <InputPopover
                            {...commonProps}
                            addonBefore={column.addonBefore}
                            value={bindObj.value}
                            />
                            )
                        } else if (column.fieldid == '-4') {//标签
                            let weatag = bindObj.value && JSON.parse(bindObj.value).map(tag => {
                                if (tag.tabname != '') {
                                    return <WeaTag title={tag.tabname} style={{
                                        borderRadius: '4px',
                                        marginBottom: 2,
                                        marginRight: 10,
                                        color: tag.color,
                                        backgroundColor: tag.bgcolor,
                                        borderColor: tag.bdcolor
                                    }}>
                            {tag.tabname.length > 10 ? `${tag.tabname.slice(0, 10)}...` : tag.tabname}
                        </WeaTag>
                    } else {
                        return tag + " ";
                    }
                });
                return (<div>{weatag}</div>)
            } else {
                if(isfrontmultlang&&column.detailtype=='1'&&!bindObj.editable&&bindObj.value.indexOf('base64_')>=0){
                    bindObj.value=getCurrentLabel(getMultiStrFromBase64(bindObj.value));
                }
                return (
                    <Input
                    {...commonProps}
                    value={bindObj.value}/>
                    )
                }
        } else if (conditionType == 'checkbox') {
            let newKey = {};
            if (column.linkedFields) {
                newKey = {key: new Date().getTime()}
            }
            return (
                <Checkbox {...newKey}
                          {...commonProps}
                          linkedFields={column.linkedFields}
                          value={bindObj.value}
                />
            )

        } else if (conditionType == 'date') {
            return (
                <div><WeaDatePicker
                    {...commonProps}
                    value={bindObj.value}
                    onChange={v => {
                        this.handleChange(v)
                    }}
                /></div>
            )
        } else if (conditionType == 'textarea') {
            if (column.viewAttr == 1) {
                return <div dangerouslySetInnerHTML={{__html: bindObj.value}}></div>
            }
            return (
                <div><WeaTextarea
                    {...commonProps}
                    value={bindObj.value}
                    onChange={v => {
                        this.handleChange(v)
                    }}
                /></div>
            )
        } else if (conditionType == 'time') {
            return (
                <div><WeaTimePicker
                    {...commonProps}
                    value={bindObj.value}
                    onChange={v => {
                        this.handleChange(v)
                    }}
                /></div>
            )
        } else if (conditionType == 'datetime') {
            return (
                <div><WeaDateTimePicker
                    {...commonProps}
                    value={bindObj.value}
                    onChange={v => {
                        this.handleChange(v)
                    }}
                /></div>
            )
        } else if (conditionType == 'select') { //选择框字段
            return (
                <Select
                    {...commonProps}
                    options={column.options ? column.options.slice() : []}
                    value={bindObj.value}
                />
            )
        } else if (conditionType == 'dialog') {
            return (
                <ShowDialog readOnly  {...commonProps} showDialog={this.showDialog} value={field && field.value}/>
            )
        } else if (conditionType == 'browser') {
            return (
                <Browser {...commonProps}/>
            )
        } else if (conditionType == 'weaupload') {
            return (
                <Upload {...commonProps}/>)
        }
        return (
            <Input
                {...commonProps}
                value={bindObj.value}
                onChange={(e) => {
                    this.handleChange(e.target.value);
                }}
            />
        )

    }

    componentDidMount() {
        const {column, randomkey, tableStore, isNoSwitchEditStatus} = this.props;
        const form = tableStore.form.$('tableForm');
        const row = form.$(randomkey);
        if (column.conditionType.toLowerCase() != 'checkbox' && !isNoSwitchEditStatus) {
            jQuery(this.refs._container).closest('td').click((e) => {
                e.preventDefault();
                if (column.changeVirtualFormFieldType) {//作用于表单，虚拟表单修改字段类型和字段属性功能
                    this.setState({_column: column.changeVirtualFormFieldType(column.key, row)});
                }
                tableStore.toEdit(randomkey, column.key);

            });
        }
        this.reRenderModifiedArea();
    }

    componentWillReceiveProps(nextProps: Readonly<TableCellProps>, nextContext: any): void {
        this.reRenderModifiedArea(nextProps);
    }

    reRenderModifiedArea = (props?) => {
        const {column, randomkey, tableStore} = props || this.props;
        const form = tableStore.form.$('tableForm');
        const row = form.$(randomkey);
        const field = row.$(column.key);
        if (field && tableStore.oldDataRecord.length > 0) {
            tableStore.oldDataRecord.forEach(el => {
                if (el._fieldid == column.fieldid && randomkey.toString().split("_")[0] == el.randomFieldId) {
                    field.value = el[column.fieldid];
                    field.modified = el.modified;
                }
            })
        }
        window['computeTableHeight']()
    }

    handleChange = (value: string, names?, datas?) => {
        const {tableStore, randomkey, column,isfrontmultlang} = this.props;
        const form = tableStore.form.$('tableForm');
        const row = form.$(randomkey);
        const field = row.$(column.key);
        const obj = {};
        let flag = false, mark = -1;
        obj[column.fieldid] = value;
        obj["_fieldid"] = column.fieldid;
        obj["randomFieldId"] = randomkey ? randomkey.toString().split("_")[0] : "";
        obj["oldValue"] = field.oldValue;
        obj["randomFieldSubKeyd_id"] = randomkey ? randomkey.toString().split("_")[1] : "";
        if(obj["oldValue"]!==undefined){
            obj["modified"] = obj[column.fieldid] !== obj["oldValue"];
        }
        if(obj["oldValue"]!==undefined&&isfrontmultlang&&column.detailtype=='1'){
            obj["modified"]=obj[column.fieldid]!==getMultiStrFromBase64(obj["oldValue"]);
        }
        tableStore.oldDataRecord = tableStore.oldDataRecord.map((v, i) => {
            if (v._fieldid == obj["_fieldid"] && v.randomFieldId == obj["randomFieldId"]&& v.randomFieldSubKeyd_id == obj["randomFieldSubKeyd_id"]) {
                v = obj;
                flag = true;
                mark = i;
            }
            return v;
        });
        if (!flag) {
            if (obj[column.fieldid] !== obj["oldValue"]) {
                tableStore.oldDataRecord.push(obj);
            }
        } else {
            if (!obj["modified"]) {
                tableStore.oldDataRecord.splice(mark, mark + 1);
            }
        }
        field.onChange && field.onChange(value, names, datas);
    }
    showDialog = () => {
        const {tableStore, randomkey} = this.props;
        let {column} = this.props;
        column = {...column, ...this.state._column};
        tableStore.showDialog(column, randomkey);
    }

    render() {
        const {tableStore, randomkey, column} = this.props;
        return (
            <span
                ref='_container'
                className="cube-mobx-table-cell"
            >
            <Badge className="cube-mobx-table-cell-badge" style={{'z-index': '1'}}
                   dot={tableStore.form.$(`tableForm.${randomkey}.${column.key}`).modified}>
                {
                    this.renderEditor()
                }
            </Badge>
            </span>
        )
    }
}
